package com.yinpeng.app.web;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class IndexController {

    @GetMapping("/")
    public String index() {
        return "hello ~";
    }

    // 显示页面(thymeleaf模板引擎)
    // session和cookie相关操作
    @RequestMapping(value = "ret-index", method = RequestMethod.GET)
    public ModelAndView mv(
            HttpServletRequest request,
            HttpServletResponse response
    ) throws ServletException, IOException {
        // 设置内容类型和编码
        response.setContentType("text/html;charset=utf-8");

        // 设置cookie及session
        // cookie
        String cookieValue = java.net.URLEncoder.encode("尹鹏", "UTF-8");
        Cookie cookie = new Cookie("name", cookieValue);
        cookie.setMaxAge(60 * 5); // 5分钟
        response.addCookie(cookie);
        // session
        HttpSession session = request.getSession();
        Date sessCreateTime = new Date(session.getCreationTime());
        Date lastAccessTime = new Date(session.getLastAccessedTime());
        String visitCountKey = "visitCount";
        int visitCount = 1; // 默认第一次访问
        String userKey = "userID";
        String user = "yinpeng";

        if (session.isNew()) {
            session.setAttribute(userKey, user); // 设置user session
        } else {
            int nowVisitCount = (int) session.getAttribute(visitCountKey);
            visitCount = ++nowVisitCount;
        }
        // 当前用户累计访问次数
        session.setAttribute(visitCountKey, visitCount);

        // 写入session和cookie
        PrintWriter writer = response.getWriter();
        try {
            writer.write("");
            writer.flush();
        } catch (Exception e) {
            // todo
            // writer log
        }

        // session 信息
        user = session.getAttribute(userKey).toString();
        visitCount = (int) session.getAttribute(visitCountKey);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("sessionid", session.getId());
        dataMap.put("sessCreateTime", df.format(sessCreateTime));
        dataMap.put("lastAccessTime", df.format(lastAccessTime));
        dataMap.put("user", user);
        dataMap.put("visitCount", visitCount);

        // thymeleaf
        // 模板注入数据及显示
        String title = "index page..";
        List<String> ps = new ArrayList<>();
        ps.add("段落1");
        ps.add("段落2");

        ModelAndView mv = new ModelAndView("index");
        mv.addObject("title", title);
        mv.addObject("ps", ps);
        mv.addObject("dataMap", dataMap);

        return mv;
    }

    // 获取请求参数值
    // 返回json
    @RequestMapping(value = "/ret-json")
    public List<Map<String, Object>> retJson(
            @RequestParam(value = "nickname", required = false) String nickname,
            @RequestParam(value = "age", required = false) String age,
            @RequestParam(value = "sex", required = false) String sex
    ) {
        nickname = nickname == null ? "默认的昵称" : nickname; // 给nickname默认值

        Map<String, Object> kv = new HashMap<>();
        kv.put("name", nickname);
        kv.put("age", age);
        kv.put("sex", sex);

        List<Map<String, Object>> al = new ArrayList<>();
        al.add(kv);

        // 匿名数据结构
        al.add(new HashMap<String, Object>() {
            {
                put("name", "haha");
                put("age", 22);
                put("sex", "nv");
            }
        });

        // 复杂结构
        al.add(new HashMap<String, Object>() {
            {
                put("name", "hrr");
                put("age", 24);
                put("sex", "女");
                put("info", new HashMap<String, Object>() {
                    {
                        put("count", 100);
                        put("ls", new ArrayList<Object>() {
                            {
                                add("22");
                                add(22);
                                add("哈哈哈");
                            }
                        });
                    }
                });
            }
        });

        return al;
    }
}
